package fun.lifepoem.dynamic.config;

import fun.lifepoem.dynamic.domain.CustRouter;
import fun.lifepoem.dynamic.mapper.CustRouterMapper;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class CustRouterConfig implements RouteDefinitionLocator {

    @Resource
    private CustRouterMapper custRouterMapper;


    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {

        System.out.println("============加载了=====");

        List<CustRouter> custRouters = custRouterMapper.selectByAll();

        List<RouteDefinition> routeDefinitions = new ArrayList<>();

        for (CustRouter custRouter : custRouters) {
            RouteDefinition e = new RouteDefinition();

            e.setUri(URI.create(custRouter.getUri()));
            e.setId(custRouter.getServiceId());
            ArrayList<PredicateDefinition> predicates = new ArrayList<>();
            predicates.add(new PredicateDefinition(custRouter.getPredicates()));
            e.setPredicates(predicates);
            routeDefinitions.add(e);
        }


        return Flux.fromIterable(routeDefinitions);
    }
}
